package org.chaos.sekiro.workorder.app.form.internal.dao

import org.chaos.sekiro.common.ktorm.AuditTable
import org.chaos.sekiro.workorder.app.form.internal.model.ComponentBindAbility
import org.ktorm.database.Database
import org.ktorm.dsl.and
import org.ktorm.dsl.eq
import org.ktorm.dsl.inList
import org.ktorm.entity.*
import org.ktorm.schema.boolean
import org.ktorm.schema.long
import org.ktorm.schema.varchar
import org.springframework.stereotype.Repository

object ComponentBindAbilities : AuditTable<ComponentBindAbility>("component_bind_abilities") {
    val id = long("id").primaryKey().bindTo { it.id }
    val userId = long("user_id").bindTo { it.userId }
    val formId = long("form_id").bindTo { it.formId }
    val componentId = long("component_id").bindTo { it.componentId }
    val abilityId = long("attribute_id").bindTo { it.abilityId }
    val value = varchar("value").bindTo { it.value }
    val enabled = boolean("enabled").bindTo { it.enabled }
}

val Database.componentBindAbilities get() = this.sequenceOf(ComponentBindAbilities)

@Repository
class ComponentBindAbilityDao(
    private val database: Database
) {

    fun findByUserIdAndFormIdAndComponentIdIn(
        userId: Long,
        formId: Long,
        componentIds: List<Long>
    ): List<ComponentBindAbility> = database.componentBindAbilities.filter {
        (it.userId eq userId) and
                (it.formId eq formId) and
                (it.componentId inList componentIds)
    }.toList()

    fun insert(entities: List<ComponentBindAbility>) {
        entities.forEach {
            database.componentBindAbilities.add(it)
        }
    }

    fun update(entities: List<ComponentBindAbility>) {
        entities.forEach {
            database.componentBindAbilities.update(it)
        }
    }

    fun deleteByUserIdAndFormIdAndComponentIdAndAbilityId(
        userId: Long,
        formId: Long,
        componentId: Long,
        abilityId: Long
    ) {
        database.componentBindAbilities.removeIf {
            (it.userId eq userId) and
                    (it.formId eq formId) and
                    (it.componentId eq componentId) and
                    (it.abilityId eq abilityId)
        }
    }
}